<template>
  <GoBack />
  <CenterBase>
    <template #CenterBase>
      <div class="header" style="margin-bottom: 28px">
        <span>复习列表</span>
      </div>
      <a-list :data-source="dataSource">
        <template #loadMore>
          <div style="text-align: center; margin-top: 20px">
            <a-button type="primary" ghost @click="loadQusDes" :disabled="disableLoad">加载更多</a-button>
          </div>
        </template>
        <template #renderItem="{ item }">
          <a-list-item>
            <span style="float: left"><a @click="jumpTo(`/detail/${item.pid}`)">{{ item.content }}</a></span>
          </a-list-item>
        </template>
      </a-list>
    </template>
  </CenterBase>
  <Footer />
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Button, List, message } from 'ant-design-vue'
import { getQusDescription, getUserReviewList } from '@/service'
import { subjectCode2Name } from '@/utils/check'
import Footer from '@/components/Footer.vue'
import CenterBase from '@/components/CenterBase.vue'
import GoBack from '@/components/GoBack.vue'
import { USER_REVIEW_LIST, USER_REVIEW_DATA } from '@/utils/constants'

interface ReviewItem {
  pid: number,
  content: string
}
export default defineComponent({
  name: 'MyReview',
  components: {
    Footer,
    CenterBase,
    AList: List,
    AListItem: List.Item,
    AButton: Button,
    GoBack
  },
  setup () {
    const router = useRouter()
    const dataSource = ref<ReviewItem[]>([])
    const loadCursor = ref<number>(0)
    const disableLoad = ref<boolean>(false)
    const reviewList = ref<number[]>([])
    const initFlag = ref<boolean>(true)

    const loadQusDes = () => {
      if (initFlag.value) {
        const cachedData = sessionStorage.getItem(USER_REVIEW_DATA)
        if (cachedData !== null) {
          initFlag.value = false
          const d = JSON.parse(cachedData)
          loadCursor.value = d.cursor
          dataSource.value = d.data
          return
        }
      }
      const batchSize = 5
      const len = reviewList.value.length
      const start = loadCursor.value
      if (start >= len) {
        message.info('已经加载全部复习题')
        disableLoad.value = true
        return
      }
      const end = Math.min(start + batchSize, len)
      const ids:number[] = []
      for (let i = start; i < end; i++) {
        ids.push(reviewList.value[i])
      }
      if (ids.length < 1) {
        return
      }
      getQusDescription(ids)
        .then(response => {
          if (response.status !== 200) {
            message.warn('请求出错')
            return
          }
          const resp = response.data
          if (resp.code !== 0 || resp.data === null) {
            message.warn('返回出错')
            return
          }
          loadCursor.value = end
          const data = resp.data as []
          data.forEach((e: any) => {
            const sub = subjectCode2Name(e.subject as string)
            const tag = e.tag as string
            const type = e.type as string
            const year = e.year as string
            const number = e.number as string
            const tags = tag.split('#')
            const showTag = tags.slice(0, 1)
            dataSource.value.push({
              content: `${type} ${sub} ${year}年第${number}题 ${showTag.join(',')}`,
              pid: e.id
            })
          })
          const cached = {
            data: dataSource.value,
            cursor: loadCursor.value
          }
          sessionStorage.setItem(USER_REVIEW_DATA, JSON.stringify(cached))
        })
    }

    const loadReviewList = () => {
      const list = sessionStorage.getItem(USER_REVIEW_LIST)
      if (list !== null) {
        reviewList.value = JSON.parse(list)
        loadQusDes()
        return
      }
      getUserReviewList()
        .then((response) => {
          if (response.status !== 200) {
            message.warn('请求出错')
          }
          const resp = response.data
          if (resp.code === 900) {
            message.info('系统还未生成你的复习列表')
            return
          }
          if (resp.code !== 0 || resp.data === null) {
            message.warn('返回出错')
            return
          }
          const pids = (resp.data as string).split('.')
          pids.forEach((v: string) => {
            reviewList.value.push(parseInt(v))
          })
          sessionStorage.setItem(USER_REVIEW_LIST, JSON.stringify(reviewList.value))
          loadQusDes()
        })
    }

    const jumpTo = (url: string) => {
      router.push(url)
    }

    onMounted(() => {
      loadReviewList()
    })
    return {
      dataSource,
      disableLoad,
      loadQusDes,
      jumpTo
    }
  }
})
</script>

<style scoped>
.header {
  text-align: center;
  margin-top: 26px;
  background-color: #1abc9c;
  border-radius: 10px;
  padding: 12px 0;
}
.header span {
  font-size: 2em;
  color: white;
  display: inline-block;
}
</style>
